<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Boss直聘数据展示系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --success-color: #4cc9f0;
            --warning-color: #f72585;
            --info-color: #4895ef;
            --light-bg: #f8f9fa;
            --dark-bg: #212529;
            --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --hover-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
        }

        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: var(--card-shadow);
            transition: all 0.3s ease;
        }

        .glass-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--hover-shadow);
        }

        .navbar-glass {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .stats-card {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border: none;
            border-radius: 15px;
            transition: all 0.3s ease;
        }

        .stats-card:hover {
            transform: translateY(-5px) scale(1.02);
            box-shadow: var(--hover-shadow);
        }

        .job-card {
            border-left: 4px solid var(--primary-color);
            transition: all 0.3s ease;
            border-radius: 10px;
        }

        .job-card:hover {
            transform: translateX(5px);
            box-shadow: var(--hover-shadow);
        }

        .salary-high {
            color: #e63946;
            font-weight: bold;
            font-size: 1.1em;
        }

        .chart-container {
            height: 300px;
            margin-bottom: 20px;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .btn-gradient {
            background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
            border: none;
            color: white;
            border-radius: 25px;
            padding: 10px 25px;
            transition: all 0.3s ease;
        }

        .btn-gradient:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .nav-tabs .nav-link {
            border: none;
            color: #6c757d;
            font-weight: 500;
            padding: 12px 25px;
            border-radius: 25px;
            margin: 0 5px;
        }

        .nav-tabs .nav-link.active {
            background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
            color: white;
        }

        .task-status {
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .status-pending { background: #fff3cd; color: #856404; }
        .status-running { background: #d1ecf1; color: #0c5460; }
        .status-completed { background: #d4edda; color: #155724; }
        .status-failed { background: #f8d7da; color: #721c24; }

        .user-menu {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 10px;
            padding: 10px;
            min-width: 200px;
        }

        .login-required {
            text-align: center;
            padding: 60px 20px;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-glass fixed-top">
    <div class="container">
        <a class="navbar-brand fw-bold" href="#">
            <i class="fas fa-chart-line me-2"></i>Boss直聘数据平台
        </a>

        <div class="navbar-nav ms-auto">
            <button class="btn btn-light me-2" onclick="showAIAssistant()">
            <i class="fas fa-robot me-1"></i> AI招聘助手
        </button>
            <div class="nav-item dropdown">
                <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="navbarDropdown" role="button"
                   data-bs-toggle="dropdown">
                    <i class="fas fa-user-circle me-2"></i>
                    <span id="navbar-username">未登录</span>
                </a>
                <ul class="dropdown-menu user-menu">
                    <li><a class="dropdown-item" href="#" onclick="showUserProfile()"><i class="fas fa-user me-2"></i>个人中心</a>
                    </li>
                    <li><a class="dropdown-item" href="#" onclick="showCrawlPanel()"><i class="fas fa-spider me-2"></i>启动爬取</a>
                    </li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li><a class="dropdown-item text-danger" href="#" onclick="logout()"><i
                            class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
                </ul>
            </div>
        </div>
    </div>
</nav>


<!-- AI助手模态框 -->
<div class="modal fade" id="aiAssistantModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-robot me-2"></i>AI招聘助手
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">请输入您的问题：</label>
                    <textarea class="form-control" id="aiQuestion" rows="3" placeholder="例如：广州一共有多少招聘职位？或者任何其他问题..."></textarea>
                    <div class="form-text">我可以回答招聘相关问题，也可以回答日常问题</div>
                </div>
                <button class="btn btn-primary w-100" onclick="askAI()">
                    <i class="fas fa-paper-plane me-2"></i>提问
                </button>

                <div class="mt-4">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0">AI回答：</label>
                        <small id="answerType" class="text-muted"></small>
                    </div>
                    <div class="card">
                        <div class="card-body bg-light" id="aiAnswer" style="min-height: 200px;">
                            <div class="text-center py-5" id="aiLoading" style="display: none;">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                                <p class="mt-2">AI正在思考中...</p>
                            </div>
                            <div id="aiResponse">
                                <p class="text-muted text-center">AI回答将显示在这里</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 对话历史 -->
                <div class="mt-3">
                    <button class="btn btn-outline-secondary btn-sm" onclick="toggleConversationHistory()">
                        <i class="fas fa-history me-1"></i>对话历史
                    </button>
                    <div id="conversationHistory" class="mt-2" style="display: none;">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">最近对话</h6>
                            </div>
                            <div class="card-body" style="max-height: 200px; overflow-y: auto;">
                                <div id="historyList">
                                    <!-- 对话历史将通过JavaScript加载 -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<div class="container mt-5 pt-5">
    <!-- 未登录提示 -->
    <div id="login-required" class="login-required" style="display: none;">
        <div class="glass-card p-5 text-center">
            <i class="fas fa-lock fa-4x text-muted mb-4"></i>
            <h3 class="mb-3">请先登录</h3>
            <p class="text-muted mb-4">您需要登录后才能查看数据</p>
            <a href="/login" class="btn btn-gradient btn-lg">立即登录</a>
        </div>
    </div>

    <!-- 已登录内容 -->
    <div id="main-content">
        <!-- 欢迎横幅 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="glass-card p-4 text-center">
                    <h1 class="display-6 fw-bold mb-3">Boss直聘数据分析平台</h1>
                    <p class="lead mb-0">实时监控招聘市场动态，洞察行业趋势</p>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-lg-3 mb-4">
                <div class="glass-card p-3">
                    <ul class="nav nav-pills flex-column" id="sidebarNav">
                        <li class="nav-item">
                            <a class="nav-link active" href="#" data-bs-toggle="tab" data-target="#dashboard">
                                <i class="fas fa-tachometer-alt me-2"></i>数据概览
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-bs-toggle="tab" data-target="#jobs">
                                <i class="fas fa-briefcase me-2"></i>职位浏览
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-bs-toggle="tab" data-target="#crawl-tasks">
                                <i class="fas fa-tasks me-2"></i>爬取任务
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" data-bs-toggle="tab" data-target="#analysis">
                                <i class="fas fa-chart-bar me-2"></i>数据分析
                            </a>
                        </li>
                    </ul>
                </div>

                <!-- 快速操作卡片 -->
                <div class="glass-card p-3 mt-3">
                    <h6 class="fw-bold mb-3"><i class="fas fa-bolt me-2"></i>快速操作</h6>
                    <button class="btn btn-gradient w-100 mb-2" onclick="showCrawlPanel()">
                        <i class="fas fa-play me-2"></i>启动爬取
                    </button>
                    <button class="btn btn-outline-primary w-100" onclick="exportData()">
                        <i class="fas fa-download me-2"></i>导出数据
                    </button>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-lg-9">
                <div class="tab-content">
                    <!-- 数据概览标签页 -->
                    <div class="tab-pane fade show active" id="dashboard">
                        <!-- 统计卡片 -->
                       <!-- 统计卡片 -->
<div class="row" id="stats-cards">
    <div class="col-md-3 mb-4">
        <div class="stats-card">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="mb-0" id="total-jobs">0</h4>
                        <p class="mb-0">总职位数</p>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-briefcase fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-4">
        <div class="stats-card">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="mb-0" id="total-cities">0</h4>
                        <p class="mb-0">覆盖城市</p>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-map-marker-alt fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-4">
        <div class="stats-card">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="mb-0" id="total-companies">0</h4>
                        <p class="mb-0">公司数量</p>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-building fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-4">
        <div class="stats-card">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="mb-0" id="latest-time">-</h4>
                        <p class="mb-0">最新数据</p>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-clock fa-2x"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

                        <!-- 图表区域 -->
                        <div class="row mt-4">
                            <div class="col-md-6 mb-4">
                                <div class="glass-card">
                                    <div class="card-body">
                                        <h5 class="card-title"><i class="fas fa-map-marker-alt me-2"></i>城市分布</h5>
                                        <div id="city-chart" class="chart-container"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6 mb-4">
                                <div class="glass-card">
                                    <div class="card-body">
                                        <h5 class="card-title"><i class="fas fa-tags me-2"></i>关键词分布</h5>
                                        <div id="keyword-chart" class="chart-container"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="glass-card">
                                    <div class="card-body">
                                        <h5 class="card-title"><i class="fas fa-money-bill-wave me-2"></i>薪资分布</h5>
                                        <div id="salary-chart" class="chart-container"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 职位浏览标签页 -->
                    <div class="tab-pane fade" id="jobs">
                        <!-- 搜索和筛选 -->
                        <div class="glass-card p-3 mb-4">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <input type="text" class="form-control" id="search-keyword"
                                           placeholder="搜索职位或关键词...">
                                </div>
                                <div class="col-md-3">
                                    <input type="text" class="form-control" id="search-city"
                                           placeholder="搜索城市...">
                                    <!--                                    <select class="form-select" id="search-city">-->
                                    <!--                                        <option value="">所有城市</option>-->
                                    <!--                                    </select>-->
                                </div>
                                <div class="col-md-3">
                                    <select class="form-select" id="search-salary">
                                        <option value="">所有薪资</option>
                                        <option value="0-10">10K以下</option>
                                        <option value="10-20">10-20K</option>
                                        <option value="20-30">20-30K</option>
                                        <option value="30+">30K以上</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <button class="btn btn-gradient w-100" onclick="loadJobs()">搜索</button>
                                </div>
                            </div>
                        </div>

                        <!-- 职位列表 -->
                        <div class="glass-card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0"><i class="fas fa-list me-2"></i>职位列表</h5>
                                <span class="text-muted" id="job-count">共 0 个职位</span>
                            </div>
                            <div class="card-body">
                                <div class="loading" id="jobs-loading">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2">正在加载数据...</p>
                                </div>
                                <div id="jobs-container"></div>

                                <!-- 分页 -->
                                <nav aria-label="Page navigation" class="mt-4">
                                    <ul class="pagination justify-content-center" id="pagination"></ul>
                                </nav>
                            </div>
                        </div>
                    </div>

                    <!-- 爬取任务标签页 -->
                    <div class="tab-pane fade" id="crawl-tasks">
                        <div class="glass-card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0"><i class="fas fa-tasks me-2"></i>我的爬取任务</h5>
                                <button class="btn btn-gradient btn-sm" onclick="showCrawlPanel()">
                                    <i class="fas fa-plus me-2"></i>新建任务
                                </button>
                            </div>
                            <div class="card-body">
                                <div id="tasks-container">
                                    <!-- 任务列表将通过JavaScript动态加载 -->
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 数据分析标签页 -->
                    <div class="tab-pane fade" id="analysis">
                        <div class="glass-card">
                            <div class="card-body text-center py-5">
                                <i class="fas fa-chart-bar fa-3x text-muted mb-3"></i>
                                <h5>数据分析功能开发中</h5>
                                <p class="text-muted">更多高级分析功能即将推出</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 登录模态框 -->
<div class="modal fade" id="loginModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">请先登录</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <p>您需要登录后才能使用此功能</p>
                <a href="/login" class="btn btn-gradient">前往登录</a>
            </div>
        </div>
    </div>
</div>

<!-- 爬取面板模态框 -->
<div class="modal fade" id="crawlPanelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-spider me-2"></i>启动数据爬取</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="crawlForm">
                    <div class="mb-3">
                        <label class="form-label">职位关键词</label>
                        <input type="text" class="form-control" name="keyword" placeholder="例如: Java, Python, 前端"
                               required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">目标城市</label>
                        <input type="text" class="form-control" name="city" placeholder="例如: 北京, 上海, 广州"
                               required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">爬取页数</label>
                        <input type="number" class="form-control" name="pages" value="5" min="1" max="20">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">爬取模式</label>
                        <select class="form-select" name="mode">
                            <option value="drissionpage">DrissionPage模式 (稳定，需登录)</option>
                            <option value="selenium">Selenium模式 (免登录)</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-gradient" onclick="startCrawl()">开始爬取</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 全局变量
    let currentUser = null;
    let currentPage = 1;
    const perPage = 20;

    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
        checkLoginStatus();
        initSidebarNavigation();
    });

    // 检查登录状态
    function checkLoginStatus() {
        const token = localStorage.getItem('authToken');
        if (token) {
            // 验证token有效性
            fetch('/api/user/profile', {
                headers: { 'Authorization': 'Bearer ' + token }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Token invalid');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    currentUser = data.data.user;
                    updateUIForLoggedInUser();
                    loadStats();
                    loadCities();
                    loadJobs();
                    loadCrawlTasks();
                } else {
                    localStorage.removeItem('authToken');
                    showLoginRequired();
                }
            })
            .catch((error) => {
                console.error('Token验证失败:', error);
                localStorage.removeItem('authToken');
                showLoginRequired();
            });
        } else {
            showLoginRequired();
        }
    }

    // 显示登录提示
    function showLoginRequired() {
        document.getElementById('login-required').style.display = 'block';
        document.getElementById('main-content').style.display = 'none';
    }

    // 更新登录用户界面
    function updateUIForLoggedInUser() {
        document.getElementById('navbar-username').textContent = currentUser.username;
        document.getElementById('login-required').style.display = 'none';
        document.getElementById('main-content').style.display = 'block';
    }

    // 初始化侧边栏导航
    function initSidebarNavigation() {
        document.querySelectorAll('#sidebarNav a').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();

                // 移除所有active类
                document.querySelectorAll('#sidebarNav a').forEach(item => {
                    item.classList.remove('active');
                });

                // 添加active类到当前项
                this.classList.add('active');

                // 隐藏所有标签页
                document.querySelectorAll('.tab-pane').forEach(pane => {
                    pane.classList.remove('show', 'active');
                });

                // 显示目标标签页
                const target = this.getAttribute('data-target');
                document.querySelector(target).classList.add('show', 'active');
            });
        });
    }

    // 显示爬取面板
    function showCrawlPanel() {
        if (!currentUser) {
            showLoginModal();
            return;
        }

        const modal = new bootstrap.Modal(document.getElementById('crawlPanelModal'));
        modal.show();
    }

    // 启动爬取
    function startCrawl() {
        const form = document.getElementById('crawlForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

            // 确保 mode 参数正确设置
    if (!data.mode) {
        data.mode = 'drissionpage'; // 默认值
    }

        fetch('/api/crawl/start', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('authToken')
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('爬取任务已启动！');
                bootstrap.Modal.getInstance(document.getElementById('crawlPanelModal')).hide();
                loadCrawlTasks(); // 刷新任务列表
            } else {
                alert('启动失败: ' + data.message);
            }
        })
        .catch(error => {
            alert('请求失败: ' + error.message);
        });
    }

    // 加载爬取任务
    function loadCrawlTasks(page = 1) {
        fetch(`/api/crawl/tasks?page=${page}&per_page=10`, {
            headers: { 'Authorization': 'Bearer ' + localStorage.getItem('authToken') }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderCrawlTasks(data.data);
            }
        })
        .catch(error => {
            console.error('加载任务失败:', error);
        });
    }


    // 渲染爬取任务
// 在renderCrawlTasks函数中改进显示
function renderCrawlTasks(tasks) {
    const container = document.getElementById('tasks-container');

    if (tasks.length === 0) {
        container.innerHTML = `
            <div class="text-center py-5">
                <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                <p class="text-muted">暂无爬取任务</p>
                <button class="btn btn-gradient" onclick="showCrawlPanel()">开始第一个任务</button>
            </div>
        `;
        return;
    }

    let html = '<div class="list-group">';
    tasks.forEach(task => {
        const statusClass = `status-${task.status}`;
        const startedAt = task.started_at ? new Date(task.started_at).toLocaleString() : '-';
        const completedAt = task.completed_at ? new Date(task.completed_at).toLocaleString() : '-';

        // 显示错误信息
        const errorInfo = task.error_message ?
            `<div class="mt-2"><small class="text-danger">错误: ${escapeHtml(task.error_message)}</small></div>` : '';

        html += `
            <div class="list-group-item">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <h6 class="mb-1">${escapeHtml(task.keyword)} - ${escapeHtml(task.city)}</h6>
                        <p class="mb-1 text-muted">
                            页数: ${task.pages} | 模式: ${task.mode || 'drissionpage'}
                            | 创建: ${new Date(task.created_at).toLocaleString()}
                        </p>
                        ${task.started_at ? `<p class="mb-1"><small>开始: ${startedAt}</small></p>` : ''}
                        ${task.completed_at ? `<p class="mb-1"><small>完成: ${completedAt}</small></p>` : ''}
                        ${errorInfo}
                    </div>
                    <div class="text-end ms-3">
                        <span class="task-status ${statusClass}">${getStatusText(task.status)}</span>
                        <div class="mt-1">
                            <small class="text-muted">结果: ${task.result_count || 0} 条</small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    html += '</div>';
    container.innerHTML = html;
}

// 获取状态文本
function getStatusText(status) {
const statusMap = {
    'pending': '等待中',
    'running': '进行中',
    'completed': '已完成',
    'failed': '失败'
};
return statusMap[status] || status;
}

// 退出登录
function logout() {
localStorage.removeItem('authToken');
currentUser = null;
window.location.href = '/login';
}

// 加载统计信息
// 修复loadStats函数
async function loadStats() {
    try {
        const token = localStorage.getItem('authToken');
        if (!token) {
            console.log('未找到token，用户未登录');
            return;
        }

        const response = await fetch('/api/stats', {
            headers: { 'Authorization': 'Bearer ' + token }
        });

        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }

        const data = await response.json();
        console.log('统计API完整响应:', data); // 调试输出

        if (data.success) {
            // 确保从data.data中获取统计信息
            const stats = data.data;
            console.log('统计数据:', stats); // 调试输出

            // 更新统计卡片
                    document.getElementById('total-jobs').textContent = data.data.total_jobs.toLocaleString();
                    document.getElementById('total-cities').textContent = data.data.total_cities;
                    document.getElementById('total-companies').textContent = data.data.total_companies.toLocaleString();
                    document.getElementById('latest-time').textContent = data.data.latest_time || '-';

                    // 绘制图表
                    renderCityChart(data.data.city_distribution);
                    renderKeywordChart(data.data.keyword_distribution);
                    renderSalaryChart(data.data.salary_distribution);
                }
            } catch (error) {
                console.error('加载统计信息失败:', error);
            }
}

// 辅助函数：更新统计卡片
function updateStatCard(elementId, value) {
    const element = document.getElementById(elementId);
    if (element) {
        if (value === null || value === undefined) {
            element.textContent = '0';
        } else if (elementId === 'latest-time') {
            element.textContent = value || '-';
        } else {
            // 如果是数字，格式化显示
            element.textContent = typeof value === 'number' ? value.toLocaleString() : value;
        }
    } else {
        console.warn(`元素 ${elementId} 未找到`);
    }
}

// 加载城市列表
async function loadCities() {
try {
    const token = localStorage.getItem('authToken');
    if (!token) return;

    const response = await fetch('/api/cities', {
        headers: { 'Authorization': 'Bearer ' + token }
    });
    const data = await response.json();

    if (data.success) {
        const citySelect = document.getElementById('search-city');
        citySelect.innerHTML = '<option value="">所有城市</option>';

        data.data.forEach(city => {
            const option = document.createElement('option');
            option.value = city;
            option.textContent = city;
            citySelect.appendChild(option);
        });
    }
} catch (error) {
    console.error('加载城市列表失败:', error);
}
}

// 加载职位列表
// 修复数据加载函数
async function loadJobs(page = 1) {
    const token = localStorage.getItem('authToken');
    if (!token) {
        showLoginRequired();
        return;
    }

    currentPage = page;
    const keyword = document.getElementById('search-keyword').value;
    const city = document.getElementById('search-city').value;
    const salary = document.getElementById('search-salary').value;

    // 显示加载动画
    document.getElementById('jobs-loading').style.display = 'block';
    document.getElementById('jobs-container').innerHTML = '';

    try {
        const params = new URLSearchParams({
            page: page,
            per_page: perPage,
            keyword: keyword,
            city: city,
            salary_range: salary
        });

        console.log('请求URL:', `/api/jobs?${params}`); // 调试输出

        const response = await fetch(`/api/jobs?${params}`, {
            headers: { 'Authorization': 'Bearer ' + token }
        });

        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }

        const data = await response.json();
        console.log('API返回数据:', data); // 调试输出

        if (data.success) {
            renderJobs(data.data);
            renderPagination(data.pagination);
            document.getElementById('job-count').textContent = `共 ${data.pagination.total} 个职位`;
        } else {
            throw new Error(data.message || '未知错误');
        }
    } catch (error) {
        console.error('加载职位列表失败:', error);
        document.getElementById('jobs-container').innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                加载失败: ${error.message}
            </div>
        `;
    } finally {
        document.getElementById('jobs-loading').style.display = 'none';
    }
}

// 渲染职位列表
function renderJobs(jobs) {
const container = document.getElementById('jobs-container');

if (jobs.length === 0) {
    container.innerHTML = `
        <div class="text-center py-5">
            <i class="fas fa-inbox fs-1 text-muted"></i>
            <p class="text-muted mt-2">暂无数据</p>
        </div>
    `;
    return;
}

let html = '';
jobs.forEach(job => {
    html += `
        <div class="card job-card mb-3">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <h5 class="card-title">${escapeHtml(job.job_title)}</h5>
                        <p class="card-text">
                            <span class="salary-high">${escapeHtml(job.job_salary)}</span>
                            | ${escapeHtml(job.job_company)}
                            | ${escapeHtml(job.company_city)}${job.job_lable ? ' | ' + escapeHtml(job.job_lable) : ''}
                        </p>
                        ${job.job_skill ? `<p class="card-text"><small class="text-muted">技能要求: ${escapeHtml(job.job_skill)}</small></p>` : ''}
                    </div>
                    <div class="col-md-4 text-end">
                        <p class="card-text"><small class="text-muted">${job.keyword}</small></p>
                        <p class="card-text"><small class="text-muted">${job.crawl_time}</small></p>
                        <button class="btn btn-outline-primary btn-sm" onclick="showJobDetail(${job.id})">查看详情</button>
                    </div>
                </div>
            </div>
        </div>
    `;
});

container.innerHTML = html;
}

// 渲染分页
function renderPagination(pagination) {
const container = document.getElementById('pagination');
const totalPages = pagination.pages;

if (totalPages <= 1) {
    container.innerHTML = '';
    return;
}

let html = '';
const maxVisible = 5;
let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
let endPage = Math.min(totalPages, startPage + maxVisible - 1);

if (endPage - startPage + 1 < maxVisible) {
    startPage = Math.max(1, endPage - maxVisible + 1);
}

// 上一页
html += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
    <a class="page-link" href="javascript:void(0)" onclick="loadJobs(${currentPage - 1})">上一页</a>
</li>`;

// 页码
for (let i = startPage; i <= endPage; i++) {
    html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
        <a class="page-link" href="javascript:void(0)" onclick="loadJobs(${i})">${i}</a>
    </li>`;
}

// 下一页
html += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
    <a class="page-link" href="javascript:void(0)" onclick="loadJobs(${currentPage + 1})">下一页</a>
</li>`;

container.innerHTML = html;
}

// 显示职位详情
async function showJobDetail(jobId) {
const modal = new bootstrap.Modal(document.getElementById('jobDetailModal'));
document.getElementById('jobDetailTitle').textContent = '职位详情';
document.getElementById('jobDetailContent').innerHTML = '<p>加载中...</p>';
modal.show();

try {
    const token = localStorage.getItem('authToken');
    const response = await fetch(`/api/job/${jobId}`, {
        headers: { 'Authorization': 'Bearer ' + token }
    });
    const data = await response.json();

    if (data.success) {
        const job = data.data;
        document.getElementById('jobDetailContent').innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <h6>职位信息</h6>
                    <p><strong>职位名称:</strong> ${escapeHtml(job.job_title)}</p>
                    <p><strong>薪资:</strong> <span class="salary-high">${escapeHtml(job.job_salary)}</span></p>
                    <p><strong>地区:</strong> ${escapeHtml(job.job_lable)}</p>
                    <p><strong>城市:</strong> ${escapeHtml(job.company_city)}</p>
                    <p><strong>关键词:</strong> ${escapeHtml(job.keyword)}</p>
                </div>
                <div class="col-md-6">
                    <h6>公司信息</h6>
                    <p><strong>公司名称:</strong> ${escapeHtml(job.job_company)}</p>
                    <p><strong>公司标签:</strong> ${escapeHtml(job.job_company_tag)}</p>
                    <p><strong>技能要求:</strong> ${escapeHtml(job.job_skill)}</p>
                    <p><strong>爬取时间:</strong> ${job.crawl_time}</p>
                </div>
            </div>
        `;
    } else {
        document.getElementById('jobDetailContent').innerHTML = '<p>加载失败</p>';
    }
} catch (error) {
    document.getElementById('jobDetailContent').innerHTML = '<p>加载失败</p>';
}
}

// 导出数据
function exportData() {
const token = localStorage.getItem('authToken');
if (!token) {
    showLoginModal();
    return;
}

const keyword = document.getElementById('search-keyword').value;
const city = document.getElementById('search-city').value;
const salary = document.getElementById('search-salary').value;

const params = new URLSearchParams({
    keyword: keyword,
    city: city,
    salary_range: salary
});

window.open(`/api/export?${params}`, '_blank');
}

// 图表渲染函数
// 修复图表渲染函数，添加错误处理
function renderCityChart(data) {
    try {
        const chartContainer = document.getElementById('city-chart');
        if (!chartContainer) {
            console.error('城市分布图表容器未找到');
            return;
        }

        const chart = echarts.init(chartContainer);

        // 确保数据格式正确
        const chartData = Array.isArray(data) ? data : [];
        const xData = chartData.map(item => item.company_city || '未知');
        const yData = chartData.map(item => item.count || 0);

        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'category',
                data: xData,
                axisLabel: {
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                data: yData,
                type: 'bar',
                itemStyle: {
                    color: '#4361ee'
                }
            }]
        };

        chart.setOption(option);

        // 如果没有数据，显示提示
        if (chartData.length === 0) {
            chart.setOption({
                title: {
                    text: '暂无数据',
                    left: 'center',
                    top: 'center',
                    textStyle: {
                        color: '#999',
                        fontSize: 14
                    }
                }
            });
        }

        // 响应窗口大小变化
        window.addEventListener('resize', function() {
            chart.resize();
        });

    } catch (error) {
        console.error('渲染城市分布图表失败:', error);
    }
}

// 类似修复其他图表函数...
function renderKeywordChart(data) {
    try {
        const chartContainer = document.getElementById('keyword-chart');
        if (!chartContainer) {
            console.error('关键词分布图表容器未找到');
            return;
        }

        const chart = echarts.init(chartContainer);
        const chartData = Array.isArray(data) ? data : [];

        const option = {
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [{
                type: 'pie',
                radius: '70%',
                data: chartData.map(item => ({
                    value: item.count || 0,
                    name: item.keyword || '未知'
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };

        chart.setOption(option);

        if (chartData.length === 0) {
            chart.setOption({
                title: {
                    text: '暂无数据',
                    left: 'center',
                    top: 'center',
                    textStyle: {
                        color: '#999',
                        fontSize: 14
                    }
                }
            });
        }

        window.addEventListener('resize', function() {
            chart.resize();
        });

    } catch (error) {
        console.error('渲染关键词分布图表失败:', error);
    }
}

function renderSalaryChart(data) {
    try {
        const chartContainer = document.getElementById('salary-chart');
        if (!chartContainer) {
            console.error('薪资分布图表容器未找到');
            return;
        }

        const chart = echarts.init(chartContainer);
        const chartData = Array.isArray(data) ? data : [];

        const option = {
                      tooltip: { trigger: 'item' },
                series: [{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    data: data.map(item => ({ value: item.count, name: item.salary_range })),
                    emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
                }]
            };
            chart.setOption(option);

        if (chartData.length === 0) {
            chart.setOption({
                title: {
                    text: '暂无数据',
                    left: 'center',
                    top: 'center',
                    textStyle: {
                        color: '#999',
                        fontSize: 14
                    }
                }
            });
        }

        window.addEventListener('resize', function() {
            chart.resize();
        });

    } catch (error) {
        console.error('渲染薪资分布图表失败:', error);
    }
}

// 添加通知函数
function showNotification(message, type = 'info') {
    // 创建一个简单的通知元素
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 5px;
        color: white;
        z-index: 10000;
        font-weight: bold;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    `;

    if (type === 'error') {
        notification.style.backgroundColor = '#dc3545';
    } else if (type === 'success') {
        notification.style.backgroundColor = '#28a745';
    } else {
        notification.style.backgroundColor = '#17a2b8';
    }

    notification.textContent = message;
    document.body.appendChild(notification);

    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// HTML转义函数
function escapeHtml(unsafe) {
if (!unsafe) return '';
return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

// 搜索框回车事件
document.getElementById('search-keyword').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
    loadJobs(1);
}
});

// 显示用户个人资料
function showUserProfile() {
const token = localStorage.getItem('authToken');
if (!token) {
    showLoginModal();
    return;
}

fetch('/api/user/profile', {
    headers: { 'Authorization': 'Bearer ' + token }
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        const user = data.data.user;
        const stats = data.data.stats;

        const modal = new bootstrap.Modal(document.getElementById('userProfileModal'));
        document.getElementById('userProfileTitle').textContent = '个人资料';
        document.getElementById('userProfileContent').innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <h6>基本信息</h6>
                    <p><strong>用户名:</strong> ${escapeHtml(user.username)}</p>
                    <p><strong>邮箱:</strong> ${escapeHtml(user.email)}</p>
                    <p><strong>注册时间:</strong> ${new Date(user.created_at).toLocaleString()}</p>
                    <p><strong>最后登录:</strong> ${user.last_login ? new Date(user.last_login).toLocaleString() : '从未登录'}</p>
                </div>
                <div class="col-md-6">
                    <h6>爬取统计</h6>
                    <p><strong>总任务数:</strong> ${stats.total_tasks || 0}</p>
                    <p><strong>完成的任务:</strong> ${stats.completed_tasks || 0}</p>
                    <p><strong>总职位数:</strong> ${stats.total_jobs || 0}</p>
                </div>
            </div>
        `;
        modal.show();
    }
})
.catch(error => {
    console.error('获取用户资料失败:', error);
});
}

// 创建用户个人资料模态框
function createUserProfileModal() {
const modalHtml = `
    <div class="modal fade" id="userProfileModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userProfileTitle">个人资料</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="userProfileContent">
                    <!-- 内容将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>
`;

document.body.insertAdjacentHTML('beforeend', modalHtml);
}

// 创建职位详情模态框
function createJobDetailModal() {
const modalHtml = `
    <div class="modal fade" id="jobDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="jobDetailTitle">职位详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="jobDetailContent">
                    <!-- 详情内容将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>
`;

document.body.insertAdjacentHTML('beforeend', modalHtml);
}

// 初始化模态框
document.addEventListener('DOMContentLoaded', function() {
createUserProfileModal();
createJobDetailModal();
});



    // 确保DOM加载完成后再初始化
document.addEventListener('DOMContentLoaded', function() {
    // 延迟执行以确保所有元素都已加载
    setTimeout(() => {
        checkLoginStatus();
        initSidebarNavigation();
    }, 100);
});




    // 显示AI助手模态框
    function showAIAssistant() {
        const modal = new bootstrap.Modal(document.getElementById('aiAssistantModal'));
        modal.show();
    }

    // 显示AI助手模态框
    function showAIAssistant() {
        const modal = new bootstrap.Modal(document.getElementById('aiAssistantModal'));
        modal.show();
        loadConversationHistory();
    }

    // 向AI提问
    function askAI() {
        const question = document.getElementById('aiQuestion').value.trim();
        if (!question) {
            alert('请输入问题');
            return;
        }

        // 显示加载状态
        document.getElementById('aiLoading').style.display = 'block';
        document.getElementById('aiResponse').innerHTML = '';
        document.getElementById('answerType').textContent = '';

        const token = localStorage.getItem('authToken');

        fetch('/api/ai/ask', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + token
            },
            body: JSON.stringify({ question: question })
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('aiLoading').style.display = 'none';

            if (data.success) {
                const answer = data.answer;
                // 显示回答类型
                document.getElementById('answerType').textContent =
                    data.is_recruitment ? '基于招聘数据' : '通用知识';
                document.getElementById('answerType').className =
                    data.is_recruitment ? 'badge bg-success' : 'badge bg-info';

                // 格式化AI回答
                const formattedAnswer = formatAIAnswer(answer);
                document.getElementById('aiResponse').innerHTML = formattedAnswer;

                // 清空问题输入框
                document.getElementById('aiQuestion').value = '';

                // 重新加载对话历史
                loadConversationHistory();
            } else {
                document.getElementById('aiResponse').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        ${data.message || '获取AI回答失败'}
                    </div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('aiLoading').style.display = 'none';
            document.getElementById('aiResponse').innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    请求失败: ${error.message}
                </div>
            `;
        });
    }

    // 格式化AI回答
    function formatAIAnswer(answer) {
        // 将回答拆分为段落
        const paragraphs = answer.split('\n\n');

        let html = '';
        for (const para of paragraphs) {
            if (para.trim()) {
                // 检查是否是列表项
                if (para.startsWith('- ') || para.startsWith('* ') || para.startsWith('• ')) {
                    const items = para.split('\n');
                    html += '<ul>';
                    for (const item of items) {
                        if (item.trim()) {
                            html += `<li>${item.substring(2)}</li>`;
                        }
                    }
                    html += '</ul>';
                } else if (para.match(/^\d+\./)) {
                    // 数字列表
                    const items = para.split('\n');
                    html += '<ol>';
                    for (const item of items) {
                        if (item.trim()) {
                            html += `<li>${item.substring(item.indexOf('.') + 1)}</li>`;
                        }
                    }
                    html += '</ol>';
                } else {
                    html += `<p>${para}</p>`;
                }
            }
        }

        return html;
    }

    // 加载对话历史
    function loadConversationHistory() {
        const token = localStorage.getItem('authToken');

        fetch('/api/ai/conversations?per_page=5', {
            headers: { 'Authorization': 'Bearer ' + token }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const historyList = document.getElementById('historyList');
                const conversations = data.data;

                if (conversations.length === 0) {
                    historyList.innerHTML = '<p class="text-muted text-center">暂无对话历史</p>';
                    return;
                }

                let html = '';
                conversations.forEach(conv => {
                    // 截短问题显示
                    const shortQuestion = conv.question.length > 30 ?
                        conv.question.substring(0, 30) + '...' : conv.question;

                    html += `
                    <div class="border-bottom pb-2 mb-2">
                        <small class="text-muted">${new Date(conv.created_at).toLocaleString()}</small>
                        <div class="fw-bold">${shortQuestion}</div>
                    </div>
                    `;
                });

                historyList.innerHTML = html;
            }
        })
        .catch(error => {
            console.error('加载对话历史失败:', error);
        });
    }

    // 切换对话历史显示
    function toggleConversationHistory() {
        const historyDiv = document.getElementById('conversationHistory');
        if (historyDiv.style.display === 'none') {
            historyDiv.style.display = 'block';
            loadConversationHistory();
        } else {
            historyDiv.style.display = 'none';
        }
    }

    // 支持回车键提交
    document.getElementById('aiQuestion').addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && e.ctrlKey) {
            askAI();
        }
    });
</script>
</body>
</html>